/*
 * Copyright 2012 Marsrutai.lt
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package lt.marsrutai.mobile.android.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.LinearLayout;

/**
 * Used as a parent layout for other layouts.
 * 
 * This layout adjusts the size of the child layout by not allowing it to get larger
 * than the predefined constant threshold.
 * 
 * @author Paulius Labanauskis
 *
 */
public class ConstrainedLayout extends LinearLayout {
    private final int MAX_WIDTH_DP = 280;
    private final float SCALE = getContext().getResources().getDisplayMetrics().density;

    public ConstrainedLayout(Context context) {
        super(context);
    }

    public ConstrainedLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        
        // Set maximum width. Prevent rounding-down with (int) cast by adding 0.5f to result.
        int maxWidth = (int) (MAX_WIDTH_DP * SCALE + 0.5f);
        
        int actualWidth = MeasureSpec.getSize(widthMeasureSpec);
        
        int adjustedWidth = Math.min(actualWidth, maxWidth);
        
        int mode = MeasureSpec.getMode(widthMeasureSpec);
        widthMeasureSpec = MeasureSpec.makeMeasureSpec(adjustedWidth, mode);
        
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}
